package com.my.study.redisson.listener;

import com.my.study.redisson.model.ClientInfo;
import com.my.study.redisson.sub.SubscribeRestThread;
import com.my.study.redisson.sub.SubscribeStartThread;
import com.my.study.redisson.timer.RedisServerTimer;
import com.my.study.util.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @author: yidujun
 * @create: 2021/11/08 15:15
 */
@Component
@Slf4j
public class ServerStartListener implements ApplicationListener<ContextRefreshedEvent> {

    @Resource
    SubscribeStartThread subscribeStartThread;

    @Resource
    SubscribeRestThread subscribeRestThread;

    @Resource
    RedisServerTimer redisServerTimer;

    private ExecutorService executor = new ThreadPoolExecutor(1, 1, 0,
            TimeUnit.SECONDS, new LinkedBlockingQueue<>(), r -> new Thread(r, ""));

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        String port = event.getApplicationContext().getEnvironment().getProperty("server.port");
        subscribeRestThread.start();
        redisServerTimer.doCheck();
        subscribeStartThread.setClientInfo(new ClientInfo(IpUtils.getLocalIp(), port));
        try {
            executor.submit(subscribeStartThread).get(Integer.MAX_VALUE, TimeUnit.SECONDS);
        } catch (InterruptedException | ExecutionException | TimeoutException e) {
            if (e instanceof InterruptedException) {
                Thread.currentThread().interrupt();
            }
            log.error("", e);
        }
    }

}
